+function($) {

	function Tdapp() {
		this.hasApp = true;
		this.time = 1000;
		this.testtime = 2000;
		this.$bottomtdappBtn = $('#bottomtdapp-btn')
		this.$toptdappBtn = $('#toptdapp-btn')
		this.notAppTopTxt = '立即下载'
		this.notAppBotTxt = '下载同道data，查看更多精彩评论 >>'
		this.appTopTxt = '立即打开'
		this.appBotTxt = '打开同道data，查看更多精彩评论  >>'
		this.url = 'tongdaodata://rogrand.tongdao.com'
		this.notAppUrl = 'http://a.app.qq.com/o/simple.jsp?pkgname=com.rogrand.tongdao'
		this.hasAppUrl = 'tongdaodata://rogrand.tongdao.com?sportinfo_id=' + this.getAppUrl('sportinfo_id') + '&sportinfo_url=http://wwww.rogrand.com'
		this.when()
	}
	Tdapp.prototype.defer = function() {
		var dtd = new jQuery.Deferred()
		var timeout
		var self = this
		var url = this.url
		
		setTimeout(function() {
			if(self.hasApp) {
				dtd.resolve('app')
			} else {
				dtd.resolve('notapp')
			}
		}, this.testtime)

		var t1 = Date.now() * 1;
		var ifr = document.createElement("iframe");
		ifr.setAttribute('src', url);
		ifr.setAttribute('style', 'display:none');
		
		document.body.appendChild(ifr);
		
		timeout = setTimeout(function() {
			var t2 = Date.now() * 1
			if(!t1 || (t2 - t1) < self.time + 100) {
				self.hasApp = false;
			}
		}, this.time)
		
		return dtd.promise();
	}
	Tdapp.prototype.when = function(){
		var self = this
		$.when($.proxy(this.defer(),this)).then(
			function(status){
				if(status == 'app'){
					self.hasApp()
				}
			},
			function(status){
				if(status == 'notapp'){
					self.notApp()
				}
			}
		)
	}
	
	Tdapp.prototype.hasApp = function(status){
		var url = this.hasAppUrl
		var topTxt = this.appTopTxt 
		var botTxt = this.appBotTxt 
		this.setAppUrl(url)
		this.setAppTxt(this.$toptdappBtn,topTxt)
		this.setAppTxt(this.$bottomtdappBtn,botTxt)
	}
	
	Tdapp.prototype.notApp = function(status){
		var url = this.notAppUrl
		var topTxt = this.notAppTopTxt 
		var botTxt = this.notAppBotTxt 
		this.setAppUrl(url)
		this.setAppTxt(this.$toptdappBtn,notAppTopTxt)
		this.setAppTxt(this.$bottomtdappBtn,notAppBotTxt)
	}
	
	Tdapp.prototype.setAppUrl = function(url){
		this.$toptdappBtn.attr('href', url)
		this.$bottomtdappBtn.attr('href', url)
	}
	
	Tdapp.prototype.setAppTxt = function($seletor,txt){
		$seletor.text(txt)
	}
	
	Tdapp.prototype.getAppUrl = function(){
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
		var r = window.location.search.substr(1).match(reg);
		if(r != null) return unescape(r[2]);
		return null;
	}
	
	$(function(){
		var tdApp = new Tdapp()
	})
}(jQuery)